# -*- coding: utf-8 -*-
import logging
import os
import sys
import time

import requests
from lxml import etree

# add up one level dir into sys path

sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))))
os.environ['DJANGO_SETTINGS_MODULE'] = 'base.settings'

from common.lottery.handler import crawl_from_opencai
from common.lottery.cyclical.js_ks.db.activity import fullfill_result
from common.lottery import LOTTERY_TYPE, OPENCAI_LOTTERY_TYPES
from common.timer import TIMER_EVENT_TYPE, TimerEvent
from common.utils import tz

URL = 'http://caipiao.163.com/award/jskuai3/'


def _parse_and_fill(resp, refer, date):
    tree = etree.HTML(resp)
    nodes = tree.xpath('//td[@data-win-number]')
    for node in nodes:
        phase = '%s%s' % (date.strftime('%Y%m%d'), node.text)
        numbers = node.attrib['data-win-number'].split(' ')
        number = ''.join(numbers)
        if number:
            activity = fullfill_result(phase, number, refer)
            if activity:
                TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.JS_KS}, tz.now_ts())

                TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.JS_KS}, tz.now_ts())
        else:
            print 'number is blank!!!!!'


def crawl_history(date):
    suffix = '?gameEn=oldkuai3&date=%s' % date.strftime('%Y%m%d')
    url = URL + suffix
    response = requests.get(url, timeout=10)
    if response.status_code != 200:
        raise RuntimeError("site down")
    _parse_and_fill(response.text, url, date)


def crawl_newest():
    '''163的爬虫
    '''
    now = tz.local_now()
    suffix = '?gameEn=oldkuai3&date=%s' % now.strftime('%Y%m%d')
    refer = URL + suffix
    response = requests.get(URL, timeout=5)
    if response.status_code != 200:
        raise RuntimeError('fail to crawl js_ks, need retry...')
    _parse_and_fill(response.text, refer, now)
    return True


def main(d):
    while True:
        try:
            crawl_from_opencai(LOTTERY_TYPE.JS_KS)
        except Exception as e:
            logging.exception(u'%s error: %s' % (OPENCAI_LOTTERY_TYPES.get(LOTTERY_TYPE.JS_KS), e))
        if d:
            break
        time.sleep(60)


if __name__ == '__main__':
    date = sys.argv[1] if len(sys.argv) > 1 else None
    main(date)
